/*
 * @filename CoreUtils.java
 * @author barry
 * @version 0.0.1
 * @date 2019年12月9日
 */
package com.bnzj.core.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.springframework.util.StringUtils;

/**
 * @author barry
 * @date 2019-12-09
 */
public class CoreUtils {
    
    /**
     * 工号格式化
     * @param userName
     * @return
     */
    public static String formatUserName(int userName) {
        return userName >= 100000 ? userName + "" : new DecimalFormat("00000").format(userName);
    }
    
    /**
     * getStrSuffix:获取字符串后缀. <br/>
     * @param str
     * @return .+后缀名: 如.txt
     * @since JDK 1.8
     */
    public static String getStrSuffix(String str){
        if(StringUtils.isEmpty(str)){
            return "";
        }
        return str.substring(str.lastIndexOf("."), str.length());
    }

    /**
     * 把中文转成Unicode码
     * 
     * @param str
     * @return
     */
    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }

    public static List<String> getLocalIPList() {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                //排除掉虚拟的网卡
                if (!networkInterface.getDisplayName().contains("Loopback")
                    && !networkInterface.getDisplayName().contains("Virtual Adapter")
                    && !networkInterface.getDisplayName().contains("Hyper-V")) {
                    inetAddresses = networkInterface.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        inetAddress = inetAddresses.nextElement();
                        if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                            ip = inetAddress.getHostAddress();
                            ipList.add(ip);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipList;
    }
}
